package token

import (
	"crypto/rsa"
	"github.com/dgrijalva/jwt-go"
	"time"
)

const Prefix = "Bearer "

type JwtTokenGen struct {
	issuer     string
	privateKey *rsa.PrivateKey
	now        func() time.Time
}

func NewJwtTokenGen(issuer string, privateKey *rsa.PrivateKey) *JwtTokenGen {
	return &JwtTokenGen{privateKey: privateKey, issuer: issuer, now: time.Now}
}

func (j *JwtTokenGen) GenerateToken(accountId string, expire time.Duration) (string, error) {

	nowSec := j.now().Unix()

	claims := jwt.NewWithClaims(jwt.SigningMethodRS512, jwt.StandardClaims{
		Issuer:    j.issuer,
		IssuedAt:  nowSec,
		ExpiresAt: nowSec + int64(expire.Seconds()),
		Subject:   accountId,
	})

	return claims.SignedString(j.privateKey)

}
